package com.yinhe.overtimecalc.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class TCPClient extends ServerClient {
    Socket socket = null;
    DataOutputStream dataOutputStream = null;
    DataInputStream dataInputStream = null;

    public TCPClient() {
    }

    @Override
    public void sendMessage(String s) {
        try {
            if (socket == null) {
                socket = new Socket(IP, PORT);
            }
            if (dataOutputStream == null) {
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
            }
            dataOutputStream.writeUTF(s);
            dataOutputStream.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getMessage() {
        String string = null;
        try {
            if (socket == null) {
                socket = new Socket(IP, PORT);
            }
            if (dataInputStream == null) {
                dataInputStream = new DataInputStream(socket.getInputStream());
            }
            string = dataInputStream.readUTF();
            System.out.println("Accept the server message:" + string);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return string;
    }

    @Override
    public void close() {
        try {
            sendMessage("exit");
            dataOutputStream.close();
            dataInputStream.close();
            socket.close();
            dataOutputStream = null;
            dataInputStream = null;
            socket = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
